package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gorm_logger "gorm.io/gorm/logger"
	"server_cluster/common/logger"
	"server_cluster/logic/game_config"
)

var Conn *gorm.DB

type GormLogWriter struct {
}

func (g *GormLogWriter) Printf(v1 string, v2 ...interface{}) {
	logger.Raw([]byte(fmt.Sprintf(v1, v2...)))
}

func InitDB() error {
	var err error
	var gormLogger gorm_logger.Interface = nil
	//if game_config.GetConfig().LogSql {
	//	gormLogger = gorm_logger.New(new(GormLogWriter), gorm_logger.Config{
	//		SlowThreshold:             200 * time.Millisecond,
	//		LogLevel:                  gorm_logger.Info,
	//		IgnoreRecordNotFoundError: false,
	//		Colorful:                  true,
	//	})
	//}
	gormLogger = gorm_logger.Default.LogMode(gorm_logger.Info)
	Conn, err = gorm.Open(mysql.Open(game_config.GetConfig().GetDbHost()), &gorm.Config{
		Logger: gormLogger,
	})
	if err != nil {
		logger.Error("%v", err)
		return err
	}
	sqlDB, err := Conn.DB()
	if err != nil {
		logger.Error("%v", err)
		return err
	}
	sqlDB.SetMaxOpenConns(int(game_config.GetConfig().DbPool))
	sqlDB.SetMaxIdleConns(int(game_config.GetConfig().DbPool))
	return nil
}
